import { Response } from 'express';
import { AuthenticatedRequest } from '../types/auth';
import prisma from '../lib/prisma';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { logger } from '../utils/logger';

export const scoringCriteriaController = {
  // 创建评分标准
  async createScoringCriteria(req: AuthenticatedRequest, res: Response) {
    try {
      const { name, description, subjectId, gradeLevel, totalScore, passingScore, rubricItems, questionScores } = req.body;

      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const criteria = await prisma.scoringCriteria.create({
        data: {
          name,
          description,
          subjectId,
          gradeLevel,
          totalScore,
          passingScore,
          creatorId: req.user.id,
          rubricItems: {
            create: rubricItems.map((item: any) => ({
              name: item.name,
              description: item.description,
              scoreRange: item.scoreRange,
              weight: item.weight
            }))
          },
          questionScores: {
            create: questionScores.map((item: any) => ({
              questionType: item.questionType,
              score: item.score
            }))
          }
        },
        include: {
          rubricItems: true,
          questionScores: true
        }
      });

      logger.info('Created scoring criteria', { criteriaId: criteria.id });
      res.status(StatusCodes.CREATED).json(criteria);
    } catch (error) {
      logger.error('Error creating scoring criteria', { error });
      throw new ApiError(StatusCodes.INTERNAL_SERVER_ERROR, '创建评分标准失败');
    }
  },

  // 获取评分标准列表
  async getScoringCriteria(req: AuthenticatedRequest, res: Response) {
    try {
      const { subjectId, gradeLevel } = req.query;

      const where = {
        ...(subjectId && { subjectId: String(subjectId) }),
        ...(gradeLevel && { gradeLevel: parseInt(String(gradeLevel)) })
      };

      const criteria = await prisma.scoringCriteria.findMany({
        where,
        include: {
          rubricItems: true,
          questionScores: true
        }
      });

      res.json(criteria);
    } catch (error) {
      logger.error('Error getting scoring criteria', { error });
      throw new ApiError(StatusCodes.INTERNAL_SERVER_ERROR, '获取评分标准失败');
    }
  },

  // 获取单个评分标准详情
  async getScoringCriteriaById(req: AuthenticatedRequest, res: Response) {
    try {
      const { id } = req.params;

      const criteria = await prisma.scoringCriteria.findUnique({
        where: { id },
        include: {
          rubricItems: true,
          questionScores: true
        }
      });

      if (!criteria) {
        throw new ApiError(StatusCodes.NOT_FOUND, '评分标准不存在');
      }

      res.json(criteria);
    } catch (error) {
      logger.error('Error getting scoring criteria by id', { error });
      throw new ApiError(StatusCodes.INTERNAL_SERVER_ERROR, '获取评分标准详情失败');
    }
  },

  // 更新评分标准
  async updateScoringCriteria(req: AuthenticatedRequest, res: Response) {
    try {
      const { id } = req.params;
      const updates = req.body;

      // 删除现有的rubricItems和questionScores
      await prisma.$transaction([
        prisma.rubricItem.deleteMany({ where: { criteriaId: id } }),
        prisma.questionScore.deleteMany({ where: { criteriaId: id } })
      ]);

      // 更新评分标准和创建新的关联数据
      const criteria = await prisma.scoringCriteria.update({
        where: { id },
        data: {
          name: updates.name,
          description: updates.description,
          subjectId: updates.subjectId,
          gradeLevel: updates.gradeLevel,
          totalScore: updates.totalScore,
          passingScore: updates.passingScore,
          rubricItems: {
            create: updates.rubricItems.map((item: any) => ({
              name: item.name,
              description: item.description,
              scoreRange: item.scoreRange,
              weight: item.weight
            }))
          },
          questionScores: {
            create: updates.questionScores.map((item: any) => ({
              questionType: item.questionType,
              score: item.score
            }))
          }
        },
        include: {
          rubricItems: true,
          questionScores: true
        }
      });

      logger.info('Updated scoring criteria', { criteriaId: id });
      res.json(criteria);
    } catch (error) {
      logger.error('Error updating scoring criteria', { error });
      throw new ApiError(StatusCodes.INTERNAL_SERVER_ERROR, '更新评分标准失败');
    }
  },

  // 删除评分标准
  async deleteScoringCriteria(req: AuthenticatedRequest, res: Response) {
    try {
      const { id } = req.params;

      await prisma.$transaction([
        prisma.rubricItem.deleteMany({ where: { criteriaId: id } }),
        prisma.questionScore.deleteMany({ where: { criteriaId: id } }),
        prisma.scoringCriteria.delete({ where: { id } })
      ]);

      logger.info('Deleted scoring criteria', { criteriaId: id });
      res.status(StatusCodes.NO_CONTENT).send();
    } catch (error) {
      logger.error('Error deleting scoring criteria', { error });
      throw new ApiError(StatusCodes.INTERNAL_SERVER_ERROR, '删除评分标准失败');
    }
  }
};
